package com.hskn.hss.task;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.config.Config;
import com.hskn.hss.module.videoconfig.entity.VideoConfig;
import com.hskn.hss.module.videoconfig.mapper.VideoConfigMapper;
import com.hskn.hss.module.videofile.entity.VideoFile;
import com.hskn.hss.module.videofile.mapper.VideoFileMapper;
import com.hskn.hss.module.videofile.vo.VideoFileVO;
import com.hskn.hss.module.videoplan.entity.VideoPlan;
import com.hskn.hss.module.videoplan.mapper.VideoPlanMapper;
import com.hskn.hss.utils.Md5Util;
import com.hskn.hss.utils.MyHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@EnableScheduling
public class VideoPlanTask {

    @Autowired
    private VideoPlanMapper videoPlanMapper;
    @Autowired
    private VideoFileMapper videoFileMapper;
    @Autowired
    private VideoConfigMapper videoConfigMapper;

    @Value("${switch.timed_task}")
    private Boolean timed_task;

    /**
     * 录像文件过期定时任务
     */
    @Scheduled(cron = "0 0 0 * * ?")
    private void expireRecordFile() {
        if (!timed_task) {
            return;
        }
        log.info("==录像文件过期定时任务--start");
        //根据录像设置中的录像保存天数，获取需要删除的录像文件进行删除
        VideoConfig videoConfig = videoConfigMapper.selectVideoConfig();
        if (null == videoConfig) {
            log.info("==录像文件过期定时任务--没有录像设置");
            return;
        }
        Integer limitDay = videoConfig.getLimitDay();
        Date limitDate = DateUtil.offsetDay(new Date(), -limitDay);
        List<VideoFileVO> list = videoFileMapper.getVideoFileForDelete(limitDate);
        if (CollectionUtils.isEmpty(list)) {
            log.info("==录像文件过期定时任务--没有过期录像文件");
            return;
        }
        for (VideoFileVO videoFileVO : list) {
            boolean flag = deleteRecordFile(videoFileVO.getEquipcode(), videoFileVO.getChannel(), videoFileVO.getVideoPlanId());
            if (flag) {
                VideoFile videoFile = new VideoFile();
                videoFile.setId(videoFileVO.getId());
                videoFile.setStatus("3");
                videoFile.setDeleteTime(DateUtil.date());
                videoFileMapper.updateById(videoFile);
            } else {
                log.error("==录像文件过期定时任务--删除过期录像文件失败,videoFileVO:{}", JSONObject.toJSONString(videoFileVO));
            }
        }
    }

    /**
     * 录像计划定时任务
     */
    @Scheduled(cron = "0/10 * * * * ?")
    private void monitor() {
        if (!timed_task) {
            return;
        }
        log.info("==录像计划定时任务--start");
        Map map = new HashMap<>();
        map.put("recordTime", DateUtil.date());
        List<VideoPlan> list = videoPlanMapper.listForHandle(map);
        if (CollectionUtils.isEmpty(list)) {
            log.info("==没有需要执行的录像计划");
            return;
        }
        for (VideoPlan videoPlan : list) {
            String fileStatus = videoPlan.getFileStatus();
            VideoFile videoFile = videoFileMapper.selectById(videoPlan.getFileId());

            if ("0".equals(fileStatus)) {//录制未开始
                boolean exist = existRecordFile(videoPlan.getEquipcode(), videoPlan.getChannel(), videoPlan.getId());
                if (exist) {
                    //更新状态
                    videoFile.setStatus("1");
                    videoFileMapper.updateById(videoFile);
                    continue;
                }
                //调用中台开始录制接口
                boolean flag = startRecord(videoPlan.getEquipcode(), videoPlan.getChannel(),
                        DateUtil.formatDateTime(videoPlan.getVideoStartTime()),
                        DateUtil.formatDateTime(videoPlan.getVideoEndTime()), videoPlan.getId());
                if (flag) {
                    //更新状态
                    videoFile.setStatus("1");
                    videoFileMapper.updateById(videoFile);
                    log.info("==调用中台开始录制接口成功");
                } else {
                    log.info("==调用中台开始录制接口失败");
                }
            } else if ("1".equals(fileStatus)) {//录制中
                //调用中台录制结果查询接口
                log.info("==调用中台录制结果查询接口,参数,deviceId:{},channelId:{},videoPlanId:{}", videoPlan.getEquipcode(), videoPlan.getChannel(), videoPlan.getId());
                JSONObject result = getRecordInfo(videoPlan.getEquipcode(), videoPlan.getChannel(), videoPlan.getId());
                log.info("==调用中台录制结果查询接口,结果,result:{}", result);
                if (null != result) {
                    String url = result.getString("name");
                    Integer size = result.getInteger("size");
                    videoFile.setUrl(url);
                    videoFile.setStatus("2");
                    videoFile.setVideoSize(size);
                    videoFileMapper.updateById(videoFile);
                }
            }
        }
    }

    /**
     * 调用中台开始录制接口
     *
     * @param deviceId
     * @param channel
     * @param startTime
     * @param endTime
     * @param videoPlanId
     * @return
     */
    public boolean startRecord(String deviceId, String channel, String startTime, String endTime, String videoPlanId) {
        String dmsAdminUrl = Config.getDmsAdminUrl() + "/api/playNVR/startRecord";
        String appId = Config.getAppId();
        String secret = Config.getSecret();
        long timestamp = DateUtil.current();
        String param = "appId=" + appId +
                "&channel=" + channel +
                "&deviceId=" + deviceId +
                "&endTime=" + endTime +
                "&startTime=" + startTime +
                "&timestamp=" + timestamp +
                "&videoPlanId=" + videoPlanId +
                "&secret=" + secret;
        String sign = Md5Util.md5(param);

        JSONObject queryParam = new JSONObject();
        queryParam.put("appId", appId);
        queryParam.put("channel", channel);
        queryParam.put("deviceId", deviceId);
        queryParam.put("startTime", startTime);
        queryParam.put("endTime", endTime);
        queryParam.put("timestamp", timestamp);
        queryParam.put("videoPlanId", videoPlanId);
        queryParam.put("sign", sign);
        String str = MyHttpUtils.sendPostJson(dmsAdminUrl, queryParam.toJSONString());
        JSONObject json = JSON.parseObject(str);
        log.info("==startRecord,result:{}", str);
        if (null == json) {
            return false;
        }
        Integer code = json.getInteger("code");
        if (code != 200) {
            return false;
        }
        return true;
    }

    /**
     * 调用中台录制结果查询接口
     *
     * @param videoPlanId
     * @return
     */
    public JSONObject getRecordInfo(String deviceId, String channel, String videoPlanId) {
        String dmsAdminUrl = Config.getDmsAdminUrl() + "/api/playNVR/getRecordInfo";
        String appId = Config.getAppId();
        String secret = Config.getSecret();
        long timestamp = DateUtil.current();
        String param = "appId=" + appId +
                "&channel=" + channel +
                "&deviceId=" + deviceId +
                "&timestamp=" + timestamp +
                "&videoPlanId=" + videoPlanId +
                "&secret=" + secret;
        String sign = Md5Util.md5(param);

        JSONObject queryParam = new JSONObject();
        queryParam.put("appId", appId);
        queryParam.put("channel", channel);
        queryParam.put("deviceId", deviceId);
        queryParam.put("timestamp", timestamp);
        queryParam.put("videoPlanId", videoPlanId);
        queryParam.put("sign", sign);
        String str = MyHttpUtils.sendPostJson(dmsAdminUrl, queryParam.toJSONString());
        JSONObject json = JSON.parseObject(str);
        log.info("==getRecordInfo,result:{}", str);
        if (null == json) {
            return null;
        }
        Integer code = json.getInteger("code");
        if (code != 200) {
            return null;
        }
        return JSONObject.parseObject(json.get("result").toString());
    }

    /**
     * 调用中台录制文件是否存在接口
     *
     * @param deviceId
     * @param channel
     * @param videoPlanId
     * @return
     */
    public boolean existRecordFile(String deviceId, String channel, String videoPlanId) {
        String dmsAdminUrl = Config.getDmsAdminUrl() + "/api/playNVR/existRecordFile";
        String appId = Config.getAppId();
        String secret = Config.getSecret();
        long timestamp = DateUtil.current();
        String param = "appId=" + appId +
                "&channel=" + channel +
                "&deviceId=" + deviceId +
                "&timestamp=" + timestamp +
                "&videoPlanId=" + videoPlanId +
                "&secret=" + secret;
        String sign = Md5Util.md5(param);

        JSONObject queryParam = new JSONObject();
        queryParam.put("appId", appId);
        queryParam.put("channel", channel);
        queryParam.put("deviceId", deviceId);
        queryParam.put("timestamp", timestamp);
        queryParam.put("videoPlanId", videoPlanId);
        queryParam.put("sign", sign);
        String str = MyHttpUtils.sendPostJson(dmsAdminUrl, queryParam.toJSONString());
        JSONObject json = JSON.parseObject(str);
        log.info("==existRecordFile,result:{}", str);
        if (null == json) {
            return false;
        }
        Integer code = json.getInteger("code");
        if (code != 200) {
            return false;
        }
        return true;
    }

    /**
     * 调用中台录制文件删除接口
     *
     * @param deviceId
     * @param channel
     * @param videoPlanId
     * @return
     */
    public boolean deleteRecordFile(String deviceId, String channel, String videoPlanId) {
        String dmsAdminUrl = Config.getDmsAdminUrl() + "/api/playNVR/deleteRecordFile";
        String appId = Config.getAppId();
        String secret = Config.getSecret();
        long timestamp = DateUtil.current();
        String param = "appId=" + appId +
                "&channel=" + channel +
                "&deviceId=" + deviceId +
                "&timestamp=" + timestamp +
                "&videoPlanId=" + videoPlanId +
                "&secret=" + secret;
        String sign = Md5Util.md5(param);

        JSONObject queryParam = new JSONObject();
        queryParam.put("appId", appId);
        queryParam.put("channel", channel);
        queryParam.put("deviceId", deviceId);
        queryParam.put("timestamp", timestamp);
        queryParam.put("videoPlanId", videoPlanId);
        queryParam.put("sign", sign);
        String str = MyHttpUtils.sendPostJson(dmsAdminUrl, queryParam.toJSONString());
        JSONObject json = JSON.parseObject(str);
        log.info("==deleteRecordFile,result:{}", str);
        if (null == json) {
            return false;
        }
        Integer code = json.getInteger("code");
        if (code != 200) {
            return false;
        }
        return true;
    }

}
